<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="../static/plugins/layui/css/layui.css">
    <link rel="stylesheet" href="../static/plugins/layui/css/formSelects-v4.css">

</head>
<style>
    .ok-body {
        padding: 10px
    }
</style>

<body>
<div class="ok-body">

    <form class="layui-form layui-form-pane" action="">
        <input type="hidden" name="deviceId" id="deviceId" th:value="${deviceId}">
        <input type="hidden"  id="modelId" th:value="${modelId}">

        <div class="layui-form-item">

            <div class="layui-inline">
                <label class="layui-form-label">故障现象</label>
                <div class="layui-input-inline">
                    <input type="text" name="symptom" autocomplete="off" placeholder="必填" lay-verify="required" class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">原因分析</label>
                <div class="layui-input-inline">
                    <input type="text" name="reason" autocomplete="off" placeholder="必填" lay-verify="required" class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item">

            <div class="layui-inline">
                <label class="layui-form-label" style="font-size: small;">故障发生时间</label>
                <div class="layui-input-inline">
                    <input type="text" name="faultTime" id="faultTime" placeholder="必填" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label" style="font-size: small;">故障解决时间</label>
                <div class="layui-input-inline">
                    <input type="text" name="solveTime" id="solveTime" placeholder="必填" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
            </div>

        </div>

        <div class="layui-form-item">

            <div class="layui-inline">
                <label class="layui-form-label" style="font-size: small;">故障排除时长</label>
                <div class="layui-input-inline">
                    <input type="text" name="duration" id="duration" lay-verify="required|duration" autocomplete="off"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label" style="font-size: small;">设备停机时长</label>
                <div class="layui-input-inline">
                    <input type="text" name="stopDuration" id="stopDuration" lay-verify="required|duration"
                           autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">分钟</div>
            </div>

        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">故障详情</label>

            <div id="faultDetail" class="faultDetails">

                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="partId" lay-verify="required" index="0" lay-filter="partId">
                            <option value="">发生故障部位</option>
                            <option value="1">机械部位</option>
                            <option value="2">电气部位</option>
                            <option value="3">液压部位</option>
                            <option value="4">气压部位</option>
                        </select>
                    </div>
                </div>

                <div class="layui-inline componentDiv">
                    <div class="layui-input-inline" style="width: 300px;">
                        <select name="changeComponent" class="changeComponent" xm-select="changeComponent0"
                                xm-select-show-count="4" xm-select-skin="normal"
                                lay-filter="changeComponent">
                            <option value=''>更换配件</option>
                        </select>
                    </div>
                </div>

            </div>

            <div class="layui-inline" style="  float: left; margin-left: 640px;margin-top: -39px;">
                <input type="button" id="addFaultPart" value="添加部位" class="layui-btn layui-btn-sm layui-btn-normal">
                <input type="button" id="deleteFaultPart" value="删除部位"
                       class="layui-btn layui-btn-sm layui-btn-danger">
            </div>

        </div>

        <div class="layui-form-item">
            <label class="layui-form-label" style="font-size: small;">主维修人员</label>
            <div class="layui-input-inline">
                <select id="masterSolver" name="masterSolver" lay-verify="required" lay-filter="masterSolver" lay-search>
                    <option value=""></option>
                </select>
            </div>
            <div class="layui-form-mid layui-word-aux">必选</div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label" style="font-size: small;" >辅助维修人员</label>
            <div class="layui-input-inline" style="width: 600px">
                <select name="solver"  xm-select="solver" xm-select-skin="normal" lay-filter="solver">
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">关键词</label>
            <div class="layui-input-inline" style="width: 600px">
                <select name="keyWordId"  xm-select="keyWord" xm-select-skin="normal"
                        lay-filter="keyWordId">
                    <option value=''>绑定关键词</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">排除过程</label>
            <div class="layui-input-block" style="width: 600px">
                <textarea name="resolvent" placeholder="请输入故障排除过程" class="layui-textarea"></textarea>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label" pane>状态</label>
            <div class="layui-input-block">
                <input type="checkbox" checked="" name="status" lay-skin="switch" value="1" lay-filter="switchTest"
                       lay-text="启用|禁用">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>

    </form>

</div>

<script src="../static/plugins/layui/layui.js"></script>
<script src="../static/js/jquery-3.2.1.min.js"></script>
<script src="../static/js/jquery.base64.js"></script>
<script src="../static/js/device.js"></script>

<script th:inline="none">
    //全局定义一次, 加载formSelects
    layui.config({
        base: '../static/plugins/layui/lay/modules/' //此处路径请自行处理, 可以使用绝对路径
    }).extend({
        formSelects: 'formSelects-v4'
    });
    layui.use(['form', 'formSelects', 'laydate', 'util'], function () {
        var form = layui.form;
        var formSelects = layui.formSelects;
        var util = layui.util;
        var laydate = layui.laydate;
        var deviceId = $('#deviceId').val();
        var modelId = $('#modelId').val();

        //故障发生时间
        laydate.render({
            elem: '#faultTime'
            , type: 'datetime'
            , max: JJZ.getNowFormatDate()
            , format: 'yyyy-MM-dd HH:mm'
            , done: function (value, date, endDate) {
                var endDateStr = JJZ.named('solveTime').val();
                var startDate = new Date(value);
                var endTime = new Date(endDateStr);
                if (endDateStr != '') {
                    if (startDate > endTime) {
                        layer.msg('故障解决时间不可能比故障发生时间更早，请仔细核对信息!', {icon: 2});
                    } else {
                        JJZ.named('duration').val(JJZ.TimeDifference(value, endDateStr));
                    }
                }
            }
        });

        //故障解决时间
        laydate.render({
            elem: '#solveTime'
            , type: 'datetime'
            , max: JJZ.getNowFormatDate()
            , format: 'yyyy-MM-dd HH:mm'
            , done: function (value, date, endDate) {
                var statrDateStr = JJZ.named('faultTime').val();
                var startDate = new Date(statrDateStr);
                var endTime = new Date(value);
                if (startDate > endTime) {
                    layer.msg('故障解决时间不可能比故障发生时间更早，请仔细核对信息!', {icon: 2});
                } else {
                    JJZ.named('duration').val(JJZ.TimeDifference(statrDateStr, value));
                }
            }
        });



        //初始化主维修人员
        JJZ.initSelectShowField(JJZ.named('masterSolver'), '/user/dataGrid', 'username', function (noError) {
            if (noError) {
                form.render();
            }
        });

        //初始化辅助维修人员下拉框
        JJZ.initMultipleSelect(formSelects, 'solver', '/user/dataGrid', 'username', function (noError) {
        });

        var componentList = [];
        //监听选择设备部位
        form.on('select(partId)', function (data) {
            var index = $(data.elem).attr('index');
            if(componentList === undefined || componentList.length == 0){
                if (modelId && modelId != '') {
                    JJZ.initMultipleSelect2(formSelects, 'changeComponent' + index, '/component/dataGridByModelId', 'modelId=' + modelId, 'name', function (noError) {
                        componentList = formSelects.value('changeComponent' + index);
                    })
                }
            }else{
                formSelects.data('changeComponent' + index, 'local', {
                    arr: componentList
                });
            }
        });

        //初始化关键词下拉框
        JJZ.initMultipleSelect(formSelects, 'keyWord', '/keyWord/dataGrid', 'name', function (noError) {
        });


        form.verify({
            //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
            duration: [
                /^[1-9]\d*$/
                , '故障排除时长必须是正整数!'
            ]
        });

        form.on('submit(submit)', function (data) {
            var masterSolver = $('#masterSolver option:selected').data();
            data.field.deviceId = deviceId;
            data.field.solveName = formSelects.value('solver', 'nameStr');
            data.field.masterSolver = masterSolver['id'];
            data.field.masterSolverName = masterSolver['username'];
            data.field.faultContent = initFaultPartContent();
            data.field.status = data.field.status == 1 ? 1 : 0;
            var startDate = new Date(util.toDateString(JJZ.named('faultTime').val()));
            var endDate = new Date(util.toDateString(JJZ.named('solveTime').val()));

            if (startDate > endDate) {
                layer.msg('故障解决时间不可能比故障发生时间更早，请仔细核对信息!', {icon: 2});
                return false
            }

            var encodeStr = $.base64.encode(JSON.stringify(data.field), 'utf-8');
            var param = 'json=' + encodeURIComponent(encodeStr);
            JJZ.requestData('/faultInfo/iframeAdd', param, function (data) {
                if(data.length>0){
                    var tipsMessage = String.format(' 本次<a style="color: red">{0}</a>配件损坏更换周期差异较大，请另外重点关注并分析根本原因',data.join(",")) ;
                    layer.open({
                        type: 1
                        ,content: '<div style="padding: 20px 50px;">'+ tipsMessage +'</div>'
                        ,btn: '知道了'
                        ,btnAlign: 'c' //按钮居中
                        ,closeBtn:0
                        ,yes: function(){
                            window.location.href =JJZ.baseUrl+ '/device/deviceDataGrid';
                            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                            parent.layer.close(index); //再执行关闭
                        }
                    });
                }else {
                    window.location.href =JJZ.baseUrl+ '/device/deviceDataGrid';
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index); //再执行关闭
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        //提交的时候用于格式化故障详情内容
        function initFaultPartContent() {
            var faultPart = [];
            //先便利所有选择好的部位信息
            $("select[name='partId'] option:selected").each(function (index, elem) {
                var temp = {};
                temp.faultPartId = $(elem).val();
                temp.faultPartName = $(elem).text();
                var changeComponents = [];
                var tempComponentIds = formSelects.value('changeComponent' + index, 'val');
                var tempComponentNames = formSelects.value('changeComponent' + index, 'name');
                for (var i in tempComponentIds) {
                    var compontentTemp = {};
                    compontentTemp.componentId = tempComponentIds[i];
                    compontentTemp.componentName = tempComponentNames[i];
                    compontentTemp.count = 1;
                    changeComponents.push(compontentTemp);
                }
                temp.changeComponent = changeComponents;
                faultPart.push(temp);
            });
            return JSON.stringify(faultPart);
        }

        //新增部位
        $('#addFaultPart').click(function () {
            var faultPartDiv = $('#faultDetail').clone();
            var index = $('div.faultDetails').length;
            $(faultPartDiv).removeAttr("id");
            $(faultPartDiv).prepend('<label class="layui-form-label" style="border: none;background-color: transparent;"></label>');

            $(faultPartDiv).find('select[name="partId"] option:selected').removeAttr('selected');

            $(faultPartDiv).find('select[name="partId"]').attr('index', index);

            $(faultPartDiv).find('div.layui-inline.componentDiv').empty();
            var html = '<div class="layui-input-inline" style="width: 300px;">' +
                '        <select name="changeComponent" class="changeComponent" xm-select="changeComponent'+index+'" xm-select-show-count="4" xm-select-skin="normal" lay-filter="changeComponent">' +
                '<option value="">更换配件</option>'+
                '         </select>' +
                '      </div>';
            $(faultPartDiv).find('div.layui-inline.componentDiv').append(html);
            $('div.faultDetails:last').after(faultPartDiv);
            form.render();
            formSelects.render('changeComponent' + index);
        });

        //删除部位
        $('#deleteFaultPart').click(function () {
            if ($('div.faultDetails').length > 1) {
                $('div.faultDetails:last').remove();
                form.render();
            }
        })

    });

    String.prototype.format = function (args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length == 1 && typeof (args) == "object") {
                for (var key in args) {
                    if (args[key] != undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] != undefined) {
                        //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                        var reg = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
        }
        return result;
    }
    String.format = function () {
        if (arguments.length == 0)
            return null;

        var str = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
            str = str.replace(re, arguments[i]);
        }
        return str;
    }
</script>
</body>
</html>